import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { v4 as uuidv4 } from 'uuid';
import { AppLoggerService } from './logger.service';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  constructor(private readonly logger: AppLoggerService) {
    this.logger.setContext('HTTP');
  }

  use(req: Request, res: Response, next: NextFunction): void {
    const { ip, method, originalUrl } = req;
    const userAgent = req.get('user-agent') || '';
    const requestId = uuidv4();

    // 为请求添加唯一ID，方便跟踪
    req['requestId'] = requestId;

    // 记录请求开始
    this.logger.log(
      `[${requestId}] ${method} ${originalUrl} - ${ip} - ${userAgent}`,
    );

    // 记录请求体（如果存在）
    if (Object.keys(req.body || {}).length > 0) {
      this.logger.debug(
        `[${requestId}] Request Body: ${JSON.stringify(req.body)}`,
      );
    }

    // 请求开始时间
    const startTime = Date.now();

    // 响应结束时的回调
    res.on('finish', () => {
      const { statusCode } = res;
      const contentLength = res.get('content-length') || 0;
      const responseTime = Date.now() - startTime;

      // 记录响应信息
      this.logger.log(
        `[${requestId}] ${method} ${originalUrl} ${statusCode} ${contentLength} - ${responseTime}ms`,
      );
    });

    // 响应关闭时的回调（通常是客户端中断连接）
    res.on('close', () => {
      const responseTime = Date.now() - startTime;
      this.logger.warn(
        `[${requestId}] ${method} ${originalUrl} - Connection closed after ${responseTime}ms`,
      );
    });

    next();
  }
}
